<template>
  <div class="city-view">
    <div class="prompt">
      你正在预览{{ cityName }}的天气信息
      <span>，可以通过右上角的"+"号按钮保存起来</span>
    </div>
    <div class="container">
      <h1>当日气温是：{{ currentWeather.temperature }}℃</h1>
      <h1>当日天气是：{{ currentWeather.weather }}</h1>
      <h1>当日风向是：{{ currentWeather.winddirection }}</h1>
      <h1>当日风力是：{{ currentWeather.windpower }}级</h1>
    </div>
    <hr>
    <div class="forecast-section">
      <div class="forecast-cards">
        <div 
          class="forecast-card"
          v-for="(cast, index) in forecasts"
          :key="index"
        >
          <span class="day">{{ formatDay(index, cast.week) }}</span>
          <span class="date">{{ formatDate(cast.date) }}</span>
          <span class="weather-type">{{ cast.dayweather }}</span>
          <span class="wind">风力 {{ cast.daypower }}级</span>
        </div>
      </div>

      <div class="temperature-chart">
        <v-chart class="chart" :option="option" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getWeather, getWeatherForecast } from '../api/weatherApi'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent } from 'echarts/components'

use([CanvasRenderer, LineChart, GridComponent])

const route = useRoute()
const cityName = ref('')
const currentWeather = ref({})
const forecasts = ref([])

// 图表配置
const option = ref({
  grid: {
    left: '5%',
    right: '5%',
    top: '15%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false,
  },
  yAxis: {
    type: 'value',
    show: false,
    min: function (value) {
      return Math.floor(value.min * 0.6)
    },
    max: function (value) {
      return Math.ceil(value.max * 1)
    }
  },
  series: [
    {
      name: '白天',
      type: 'line',
      data: [],
      symbolSize: 12,
      symbol: 'circle',
      smooth: true,
      lineStyle: { 
        width: 3, 
        color: '#7EB3FF' 
      },
      itemStyle: { 
        color: '#7EB3FF', 
        borderWidth: 2, 
        borderColor: '#fff' 
      },
      label: {
        show: true,
        position: 'top',
        formatter: '白{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 4
      }
    },
    {
      name: '夜间',
      type: 'line',
      data: [],
      symbolSize: 12,
      symbol: 'circle',
      smooth: true,
      lineStyle: { 
        width: 3, 
        color: '#A7E25F' 
      },
      itemStyle: { 
        color: '#A7E25F', 
        borderWidth: 2, 
        borderColor: '#fff' 
      },
      label: {
        show: true,
        position: 'bottom',
        formatter: '晚{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 4
      }
    }
  ]
})

// 日期格式化
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 星期格式化
const formatDay = (index, week) => {
  const weekMap = ['日', '一', '二', '三', '四', '五', '六']
  // 前两日特殊处理
  if (index === 0) return '今天';
  if (index === 1) return '明天';
  
  return `周${weekMap[week % 7] || ''}`;
  
}

// 获取天气数据
onMounted(async () => {
  try {
    const adcode = route.params.adcode
    
    // 获取实时天气
    const liveData = await getWeather(adcode)
    if (liveData) {
      currentWeather.value = liveData
      cityName.value = liveData.city
    }

    // 获取天气预报
    const forecastRes = await getWeatherForecast(adcode)
    if (forecastRes?.casts) {
      // 处理每个预报项目的week数据
      forecasts.value = forecastRes.casts.slice(0, 4).map(cast => ({
        ...cast,
        // 确保week是有效的，API可能返回1-7的数字或"星期x"格式
        week: cast.week || String(new Date(cast.date).getDay())
      }))
      
      // 更新图表配置
      option.value = {
        ...option.value,
        xAxis: {
          ...option.value.xAxis,
          data: forecasts.value.map((cast, index) => formatDay(index, cast.week))
        },
        series: [
          {
            ...option.value.series[0],
            data: forecasts.value.map(c => parseInt(c.daytemp))
          },
          {
            ...option.value.series[1],
            data: forecasts.value.map(c => parseInt(c.nighttemp))
          }
        ]
      }
    }
  } catch (error) {
    console.error('数据加载失败:', error)
  }
})
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.city-view {
  opacity: 1;
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  border-width: 0;
  
  .prompt{
    text-align: center;
    padding: .5rem;
    background-color: #004e71;
  }
  
  .container{
    text-align: center;
    gap: 1rem;
    flex-direction: column;
    display: flex;
    margin-top: 1.5rem;
    max-width: 1024px;
    margin-right: auto;
    margin-left: auto;
    padding-right: 10rem;
    padding-left: 10rem;
    
    h1{
      margin: 0;
      font-size: inherit;
      font-weight: inherit;
    }
  }
  
  hr{
    border-color: rgba(255, 255, 255, 0.2);
    margin-top: 1.5rem;
    border-top-width: 1px;
  }
  
  .forecast-section {
    margin-top: 8px;
    padding: 0 300px;

    .forecast-cards {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0;
      background-color: #004e71;
      border-radius: 8px 8px 0 0;
      padding: 1.5rem 1.5rem 0 1.5rem;

      .forecast-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        padding: 1rem;
        gap: 1rem;
        text-align: center;
        height: 150px;
        width: 100px;
      }
    }

    .temperature-chart {
      position: relative;
      width: 100%;
      height: 300px;
      padding: 1.5rem;
      margin-bottom: 2rem;
      background-color: #004e71;
      padding: 1.5rem 1.5rem 0 1.5rem;
      
      .chart {
        position: absolute;
        left: 0;
        top: 0;
        width: 90%;
        height: 100%;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        padding: 1.5rem; 
        margin-left: 40px;
        border-width: 0;
      }
    }
  }
}
</style>
